import os

from django.shortcuts import render, render_to_response
from django.http import HttpResponse, HttpResponseRedirect
from django.conf import settings
from django.db import connection, transaction

from PIL import Image
import numpy as np

ICON_ON_PAGE = 18

# Create your views here.
def mainpage(request):
	if 'page' in request.GET:
		currPage = int(request.GET['page'])
	else:
		currPage = 1

	allPages = len(os.listdir(settings.PATH_TO_BASED_ICON)) / ICON_ON_PAGE + 1

	if currPage > allPages:
		currPage = allPages

	iconsName = os.listdir(settings.PATH_TO_BASED_ICON)[ICON_ON_PAGE*(currPage-1) : ICON_ON_PAGE*currPage]
	icnCnt = 0
	icons1 = []
	icons = []
	iconsRow = []

	if 'color' in request.GET:
		color = request.GET['color']

		existColor = os.listdir(settings.PATH_TO_COLORED_ICON)
		if not color in existColor:
			os.makedirs(settings.PATH_TO_COLORED_ICON + "\\" + color)

		r1, g1, b1 = 0, 0, 0 # Original value
		rw = int(color[0:2], 16)
		gw = int(color[2:4], 16)
		bw = int(color[4:6], 16)
		aw = 255 # Value that we want to replace features with
		for image in iconsName:
			im = Image.open(settings.PATH_TO_BASED_ICON+image)
			im = im.convert('RGBA')
			data = np.array(im)

			red, green, blue, alpha = data[:,:,0], data[:,:,1], data[:,:,2], data[:,:,3]

			mask = alpha != 0
			data[..., :-1][mask] = (rw, gw, bw)

			im = Image.fromarray(data)
			print settings.PATH_TO_COLORED_ICON+color+"\\"+image
			im.save(settings.PATH_TO_COLORED_ICON+color+"\\"+image)
			icons1.append(settings.PATH_TO_COLORED_ICON+color+"\\"+image)

	if 'color' in request.GET:
		myDict = icons1
	else:
		myDict = iconsName

	cursor = connection.cursor()
	for ic in myDict:
		if len(ic.split('\\')) > 1:
			ic = ic.split('\\')[-2] + '\\' + ic.split('\\')[-1]
		query = "SELECT iconname FROM icons WHERE iconfilename = '%s'"%(ic)
		cursor.execute(query)
		name = cursor.fetchone()
		if name != None:
			name = name[0]
		else: name = ic

		iconsRow.append({	'file' 	: 	ic,
							'name'	:	name	})
		if len(iconsRow) == 6:
			icons.append(iconsRow)
			iconsRow = []

	if len(iconsRow) != 0:
		icons.append(iconsRow)


	return render_to_response('main.html', {'pageType'	:	'startPage',
											'icons'		: 	icons,
											'allPages'	:	allPages,
											'currPage'	:	currPage})

@transaction.commit_on_success
def uploadIcon(request):
	if request.method == 'POST':
		if request.FILES == None:
				return render_to_response('main.htnl', {'variable':'NO FILE'})
		else:
			if request.FILES.has_key("attachedfile") == True:
				if len(os.listdir(settings.PATH_TO_BASED_ICON)) == 0:
					name = '0001.png'
				else:
					lastName = os.listdir(settings.PATH_TO_BASED_ICON)[len(os.listdir(settings.PATH_TO_BASED_ICON))-1]
					name = str(int(lastName.replace('.png',''))+1).zfill(4) + '.png'
				data = request.FILES['attachedfile']
				filePath = settings.PATH_TO_BASED_ICON + name
				destination = open(filePath, 'wb')
				for chunk in data.chunks():
					destination.write(chunk)

				destination.close()
				createBlack(Image.open(filePath)).save(filePath)

				cursor = connection.cursor()
				query = "INSERT INTO icons (iconfilename, icontags, iconname) VALUES ('%s', '%s', '%s');" %(name, request.POST['iconTag'], request.POST['iconName'])
				cursor.execute(query)

	return mainpage(request)
				
def uploadImagePage(request):
	if 'ownerUserLogin' in request.session and request.session['ownerUserLogin'] == True:
		return render_to_response('main.html', {'pageType'	:	'uploadIcon'})
	
	return HttpResponseRedirect("/login/")

def viewIcon(request):
		return render_to_response('main.html', {'pageType'	:	'viewer',
												'icon'		: 	request.GET['icon'],
												'color'		:	request.GET['color']})

def createBlack(img):
	img = img.convert("RGBA")
	pixdata = img.load()

	# Clean the background noise, if color != white, then set to black.

	for y in xrange(img.size[1]):
		for x in xrange(img.size[0]):
			if pixdata[x, y][3] == 0:
				pixdata[x, y] = (255, 255, 255, 0)
			else:
				pixdata[x, y] = (0, 0, 0, pixdata[x, y][3])

	return img